(function () {

	if (!window.$config) {
		window.$config = {
			network: (function () {
				return {
					//domain: 'http://127.0.0.1:8080',
					baseContent: '',
					contentPath: '',
					loginPage: '/login',
					logoutPage: '/logout',
					myTypeName: 'My-Type',
					myType: 'rest',
					tokenStartStr: '',
					tokenHeaderName: 'access-token',
					tokenName: 'access-token',
					mesTokenName: 'TOKEN',
					cookieName: 'silly_token',
					connectTimeout: 600000
				};
			})()
		};
	}
})();
/**
 * 封装http请求
 */
(function () {

	let networkConfig = $config.network;

	window.axios.defaults.timeout = networkConfig.connectTimeout;
	window.axios.defaults.baseURL = '';

	// ==================================== token 相关操作 ============================================================

	let setToken = function (token) {
		localStorage.setItem(networkConfig.tokenName, networkConfig.tokenStartStr + token);
		localStorage.setItem(networkConfig.mesTokenName, token);
	};

	let getToken = function () {
		let token = localStorage.getItem(networkConfig.tokenName);
		if (!token) {
			token = getQueryVariable(networkConfig.tokenName);
			if (token) {
				setToken(token);
			}
		}
		return token;
	};

	let delToken = function () {
		localStorage.removeItem(networkConfig.tokenName);
		localStorage.removeItem(networkConfig.mesTokenName);
	};

	let toLoginPage = function () {
		window.location.reload();
	};

	let logout = function () {
		delToken();
		window.location.href = networkConfig.logoutPage;
	};

	networkConfig.setToken = setToken;
	networkConfig.getToken = getToken;
	networkConfig.delToken = delToken;
	networkConfig.logout = logout;
	networkConfig.toLoginPage = toLoginPage;


	function getQueryVariable(variable) {
		let query = window.location.search.substring(1);
		let vars = query.split("&");
		for (let i = 0; i < vars.length; i++) {
			let pair = vars[i].split("=");
			if (pair[0] === variable) {
				return pair[1];
			}
		}
		return (false);
	}

	// ==================================== response状态码 相关操作 ===================================================

	function responseStatusHandle(status) {
		switch (status) {
			case 401: {
				toLoginPage();
				break;
			}
			case 403: {
				toLoginPage();
				break;
			}
			default: {

			}
		}
	}

	// ==================================== http request 拦截器 =======================================================
	axios.interceptors.request.use(
		function (config) {

			config.headers = {
				'Content-Type': 'application/x-www-form-urlencoded',
				'Cache-Control': 'no-cache',
				'Pragma': 'no-cache',
				'X-Requested-With': 'XMLHttpRequest',
			};
			config.headers[networkConfig.myTypeName] = networkConfig.myType;

			if (config.method === 'post' && config.headers["Content-Type"] === "application/x-www-form-urlencoded") {
				config.data = Qs.stringify(config.data, {
					allowDots: true,
					skipNulls: true
				});
			}

			if (config.url.indexOf('/login') === -1) {
				let token = getToken();
				if (token) {
					config.headers[networkConfig.tokenHeaderName] = token;
				}
			}
			return config;
		},
		function (error) {
			return Promise.reject(error);
		}
	);

	// ==================================== http response 拦截器 ======================================================
	axios.interceptors.response.use(
		function (response) {
			if (response && response.headers && response.headers.delToken) {
				delToken();
			}
			if (response && response.data && response.data.token) {
				let token = response.data.token;
				setToken(token);
			}
			if (response && response.headers && response.headers.token) {
				let token = response.headers.token;
				setToken(token);
			}
			if (response && response.headers && response.headers[networkConfig.tokenHeaderName]) {
				let token = response.headers[networkConfig.tokenHeaderName];
				setToken(token);
			}
			return response;
		},
		function (error) {
			if (error.response) {
				responseStatusHandle(error.response.status);
			}
			return Promise.reject(error)
		}
	);

	function ajax(conf) {
		if (conf !== undefined) {
			let _axios = axios.create({
				baseURL: conf.baseURL === undefined ? axios.defaults.baseURL : conf.baseURL,
				timeout: conf.timeout === undefined ? axios.defaults.timeout : conf.timeout,
				headers: conf.headers === undefined ? null : conf.headers
			});
			_axios.interceptors.request.use(
				function (config) {
					if (config.method === 'post' && config.headers["Content-Type"] === "application/x-www-form-urlencoded") {
						config.data = Qs.stringify(config.data, {
							allowDots: true,
							skipNulls: true
						});
					}
					return config;
				},
				function (error) {
					return Promise.reject(error);
				}
			);
			return _axios;
		}
		return axios;
	}


	/**
	 * 封装get方法
	 * @param url
	 * @param params
	 * @returns {Promise}
	 */

	function get(url, params) {
		if (params === undefined) {
			params = {}
		}
		return new Promise(function (resolve, reject) {
			ajax().get(url, {params: params})
				.then(function (response) {
					resolve(response.data);
				})
				.catch(function (err) {
					reject(err)
				})
		})
	}


	/**
	 * 封装post请求
	 * @param url
	 * @param data
	 * @param conf
	 * @returns {Promise}
	 */
	function post(url, data, conf) {

		if (data === undefined) {
			data = {}
		}

		return new Promise(function (resolve, reject) {
			ajax(conf).post(url, data, conf)
				.then(function (response) {
					resolve(response.data);
				}, function (err) {
					reject(err)
				})
		})
	}

	function postJson(url, data, conf) {

		if (data === undefined) {
			data = {}
		}
		data = JSON.stringify(data);
		conf = {headers: {"Content-Type": "application/json"}};
		return new Promise(function (resolve, reject) {
			ajax(conf).post(url, data, conf)
				.then(function (response) {
					resolve(response.data);
				}, function (err) {
					reject(err)
				})
		})
	}


	/**
	 * 封装patch请求
	 * @param url
	 * @param data
	 * @param conf
	 * @returns {Promise}
	 */

	function patch(url, data, conf) {

		if (data === undefined) {
			data = {}
		}
		return new Promise(function (resolve, reject) {
			ajax(conf).patch(url, data, conf)
				.then(function (response) {
					resolve(response);
				}, function (err) {
					reject(err)
				})
		})
	}

	/**
	 * 封装put请求
	 * @param url
	 * @param data
	 * @param conf
	 * @returns {Promise}
	 */
	function put(url, data, conf) {

		if (data === undefined) {
			data = {}
		}
		return new Promise(function (resolve, reject) {
			ajax(conf).put(url, data, conf)
				.then(function (response) {
					resolve(response.data);
				}, function (err) {
					reject(err)
				})
		})
	}

	var ajaxSetup = {
		beforeSend: function (jqXHR) {
			jqXHR.setRequestHeader(networkConfig.tokenHeaderName, getToken());
			jqXHR.setRequestHeader(networkConfig.myTypeName, networkConfig.myType);
		},
		error: function (jqXHR) {
			responseStatusHandle(jqXHR.status);
		},
		complete: function (jqXHR) {
			if (jqXHR && jqXHR.getResponseHeader) {
				let token = jqXHR.getResponseHeader(networkConfig.tokenHeaderName);
				if (token) {
					setToken(token)
				}
			}
		}
	};

	(function () {
		if (window.$ && window.$.ajaxSetup) {
			window.$.ajaxSetup(ajaxSetup);
		}
	})();


	let http = {
		get: get,
		post: post,
		postJson: postJson,
		put: put,
		patch: patch,
		getToken: getToken,
		ajaxSetup: ajaxSetup
	};

	if (typeof my !== "object") {
		window.my = {
			baseContent: $config.network.baseContent,
			base: $config.network.contentPath
		};
	}
	window.my.http = http;
}());
